#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <string.h>

#ifdef NON_OS

#else
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#endif

#include <config.h>

#ifdef GPU_SUPPORT

#include <types.h>
#include <systems.h>
#include <gapi.h>
#include <drivers/graphic/gpu.h>
#include <drivers/graphic/glt.h>
#include <drivers/graphic/videoin.h>

extern int xres, yres, bpp, fbsize, fb;

void vi_enable()
{
    u32 ctrl;
    
    /* Video-in input */
    ioctl(fb, FBIOCTL_GET_VI_CTRL, &ctrl);
    ctrl |= VI_CONTROL_EN;
    vi_control(ctrl);
    
    /* GPU Video-in output 
    ioctl(fb, FBIOCTL_GET_CTRL, &ctrl);
    ctrl |= REG_CONTROL_VIDEO_EN;
    ioctl(fb, FBIOCTL_SET_CTRL, &ctrl); */
}

void vi_disable()
{
    u32 ctrl;
    
    /* Video-in input */
    ioctl(fb, FBIOCTL_GET_VI_CTRL, &ctrl);
    ctrl &= ~VI_CONTROL_EN;
    vi_control(ctrl);
    
    /* GPU Video-in output 
    ioctl(fb, FBIOCTL_GET_CTRL, &ctrl);
    ctrl &= ~REG_CONTROL_VIDEO_EN;
    ioctl(fb, FBIOCTL_SET_CTRL, &ctrl); */
}

void vi_control(u32 ctrl)
{
    u32 data = ctrl;
    ioctl(fb, FBIOCTL_SET_VI_CTRL, &data);
    sleep(1);
}

void vi_set_fb_addr(u32 addr)
{
    u32 address = addr;
    ioctl(fb, FBIOCTL_SET_VIBASE, &address);
}

void vi_set_frame_size(u16 width, u16 height)
{
    u16 dat[2] = { width, height };
    ioctl(fb, FBIOCTL_SET_VI_FRMSZ, dat);
}

u32 vi_get_fb_addr(void)
{
    u32 address;
    ioctl(fb, FBIOCTL_GET_VIBASE, &address);
    return address;
}

void vi_info()
{
    u32 vga2_fb_base;
    u32 vi_fb_base;
    u32 vi_height;
    u32 vi_width;
    u32 vi_control;
    u32 vi_lines;
    u32 vi_pixels;
    
    ioctl(fb, FBIOCTL_GET_FBVGA2BASE, &vga2_fb_base);
    ioctl(fb, FBIOCTL_GET_VIBASE, &vi_fb_base);
    ioctl(fb, FBIOCTL_GET_VI_HEIGHT, &vi_height);
    ioctl(fb, FBIOCTL_GET_VI_WIDTH, &vi_width);
    ioctl(fb, FBIOCTL_GET_VI_CTRL, &vi_control);
    ioctl(fb, FBIOCTL_GET_VI_LINE, &vi_lines);
    ioctl(fb, FBIOCTL_GET_VI_PIXEL, &vi_pixels);
    
    DPRINTF("VGA2 Base: 0x%x\n"
            "VideoIn Base: 0x%x\n"
            "VideoIn Height: %d\n"
            "VideoIn Width: %d\n"
            "VideoIn Control: 0x%x\n"
            "VideoIn Lines: %d\n"
            "VideoIn Pixels: %d\n"
            , vga2_fb_base, 
            vi_fb_base, vi_height, vi_width, 
            vi_control, vi_lines, vi_pixels);
}

#endif
